import * as THREE from "three"
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';

export default class ThreeTool {
  constructor(container, canvas) {
    this.container = container;//canvas包裹容器
    this.canvas = canvas;//canvas
    this.clock = new THREE.Clock();//场景时间
    this.scene = this.initScene();
    this.camera = this.initCamera();
    this.controls = this.initControls();
    this.light = this.initLight();
    this.renderer = this.initRenderer()
    //解决调用tick丢失this
    this.tick = this.tick.bind(this)
    //创建场景
    this.createScene();
  }
  initCamera() {
    const cameraParms = {
      fov: 75,// 摄像机视锥体垂直视野角度
      aspect: 1,// 摄像机视锥体长宽比
      near: 0.1,//摄像机视锥体近端面
      far: 100,// 摄像机视锥体远端面
    }
    let { fov, aspect, near, far } = cameraParms
    let position = new THREE.Vector3(0, 0, 3)

    const camera = new THREE.PerspectiveCamera(fov, aspect, near, far)


    camera.position.set(position.x, position.y, position.z)

    return camera
  }
  initControls() {
    const controls = new OrbitControls(this.camera, this.canvas);
    controls.update()
    return controls
  }
  initScene() {
    const scene = new THREE.Scene()
    return scene
  }
  initRenderer() {
    const renderer = new THREE.WebGLRenderer({
      canvas: this.canvas
    })
    renderer.setSize(this.canvas.width, this.canvas.height)
    // renderer.setSize(window.innerWidth, window.innerHeight)
    return renderer
  }

  initLight(color = 0xffffff, intensity = 1) {
    const light = new THREE.AmbientLight(color, intensity);
    light.position.set(3, 3, 3);
    return light;
  }
  resize(width, height) {
    const aspect = width / height
    // Update camera
    this.camera.aspect = aspect
    this.camera.updateProjectionMatrix()

    // Update renderer
    this.renderer.setSize(width, height)
    this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))
  }
  tick() {
    const elapsedTime = this.clock.getElapsedTime()

    // Update controls
    this.controls.update()

    // Render
    this.renderer.render(this.scene, this.camera)
    // Call tick again on the next frame
    window.requestAnimationFrame(this.tick)


  }
  createScene() {

    this.scene.add(this.camera)
    this.scene.add(this.light)
    const axesHelper = new THREE.AxesHelper(1);
    this.scene.add(axesHelper);

    this.tick();
  }
}

